﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Reflection;

namespace Marbles.Core.Content.Analytics
{
    public abstract class AnalyticsEngine
    {

        public static WebControl GetEngine(string engine, string[] settings)
        {
            if (string.IsNullOrEmpty(engine)) { return null; }
            WebControl control = null;
            Assembly assm = Assembly.GetAssembly(typeof(AnalyticsEngine));

            foreach (Type t in assm.GetTypes())
            {
                if (t.GetInterface("IAnalyticsControl") != null)
                {
                    control = (WebControl)Activator.CreateInstance(t);
                    if (((IAnalyticsControl)control).EngineName.ToLower() == engine.ToLower())
                    {
                        control.ID = "cAnalyticsControl";
                        ((IAnalyticsControl)control).Settings = ParseSettings(settings);
                        return control;
                    }
                    control = null;
                }
            }

            return null;
        }

        public static Dictionary<string, string> GetInstalledEngines()
        {
            Dictionary<string, string> items = new Dictionary<string, string>();

            Assembly assm = Assembly.GetAssembly(typeof(AnalyticsEngine));

            foreach (Type t in assm.GetTypes())
            {
                if (t.GetInterface("IAnalyticsControl") != null)
                {
                    IAnalyticsControl control = (IAnalyticsControl)Activator.CreateInstance(t);
                    items.Add(control.EngineName, control.Title);
                }
            }

            return items;
        }

        private static Dictionary<string, string> ParseSettings(string[] settings)
        {
            Dictionary<string, string> items = new Dictionary<string, string>();
            if (settings.Length == 0) { return items; }

            foreach (string value in settings)
            {
                if (string.IsNullOrEmpty(value.Trim())) { continue; }
                string[] args = value.Trim().Split('=');
                items.Add(args[0].Trim().ToUpper(), args[1].Trim());
            }

            return items;
        }
    }
}
